#!/usr/bin/env node

require('dotenv').config();
const Client = require('ftp');
const chalk = require('chalk');

class SimpleUploadTest {
    constructor() {
        this.host = process.env.FTP_HOST;
        this.port = parseInt(process.env.FTP_PORT) || 21;
        this.user = process.env.FTP_USER;
        this.password = process.env.FTP_PASSWORD;
        this.client = new Client();
    }

    async testUpload() {
        console.log(chalk.blue('🧪 简单上传测试'));
        console.log(chalk.gray('=' .repeat(40)));
        
        // 测试不同的模式和配置
        const testConfigs = [
            { name: '主动模式', passive: false },
            { name: '被动模式', passive: true },
            { name: '主动模式+短超时', passive: false, timeout: 15000 },
            { name: '被动模式+短超时', passive: true, timeout: 15000 }
        ];

        for (const config of testConfigs) {
            console.log(chalk.yellow(`\n测试配置: ${config.name}`));
            const success = await this.testSingleUpload(config);
            if (success) {
                console.log(chalk.green(`✅ ${config.name} 上传成功！`));
                return true;
            }
        }
        
        console.log(chalk.red('❌ 所有配置都上传失败'));
        return false;
    }

    async testSingleUpload(config) {
        return new Promise((resolve) => {
            const client = new Client();
            let resolved = false;

            const cleanup = () => {
                if (!resolved) {
                    resolved = true;
                    client.destroy();
                }
            };

            const timeout = setTimeout(() => {
                console.log(chalk.red(`  ❌ ${config.name} 上传超时`));
                cleanup();
                resolve(false);
            }, (config.timeout || 30000) + 5000);

            client.on('ready', () => {
                console.log(chalk.green(`  ✓ ${config.name} 连接成功`));
                
                // 尝试上传测试文件
                client.put('./test.txt', '/test_upload.txt', (err) => {
                    clearTimeout(timeout);
                    
                    if (err) {
                        console.log(chalk.red(`  ❌ ${config.name} 上传失败: ${err.message}`));
                        cleanup();
                        resolve(false);
                    } else {
                        console.log(chalk.green(`  ✓ ${config.name} 文件上传成功`));
                        
                        // 验证上传是否成功
                        client.size('/test_upload.txt', (sizeErr, size) => {
                            if (sizeErr) {
                                console.log(chalk.yellow(`  ⚠ ${config.name} 无法验证文件大小`));
                            } else {
                                console.log(chalk.green(`  ✓ ${config.name} 文件大小: ${size} 字节`));
                            }
                            
                            cleanup();
                            resolve(true);
                        });
                    }
                });
            });

            client.on('error', (err) => {
                console.log(chalk.red(`  ❌ ${config.name} 连接失败: ${err.message}`));
                clearTimeout(timeout);
                cleanup();
                resolve(false);
            });

            const connectionOptions = {
                host: this.host,
                port: this.port,
                user: this.user,
                password: this.password,
                passive: config.passive,
                pasvTimeout: config.timeout || 30000,
                connTimeout: Math.min(config.timeout || 30000, 15000)
            };

            console.log(chalk.gray(`  连接配置: passive=${config.passive}, timeout=${config.timeout || 30000}`));
            client.connect(connectionOptions);
        });
    }
}

if (require.main === module) {
    const test = new SimpleUploadTest();
    test.testUpload()
        .then(() => process.exit(0))
        .catch(console.error);
}

module.exports = SimpleUploadTest;